/**
 * 上传视频组件 配合form组件使用
 * @Author: linzy
 * @Date: 2022-08-30
 * @function Video
 * @param {number} isNormal=true - 是否是普通模式
 * @param {number} listType=picture-card - 上传视频的展示模式
 * @param {number} accept=.mp4 - 上传的文件类型
 * @param {*} ... - antd Upload组件属性
 * @example
 *  <Video />
 */
import React, { useState } from "react";
import { Icon } from "antd";
import { DJOssUpload } from "@/components";
import { setDefaultAttrs } from "@/hooks/tools";
import { message } from "antd";

export default (props) => {
  setDefaultAttrs(props, {
    isNormal: true,
    listType: "picture-card",
    accept: ".mp4",
  });
  const { fileList = [], onChange, ...restProps } = props;
  const [loading, loadingSet] = useState(false);
  const handlePreview = (file) => {
    if (file && file.response) {
      let video = file.response.viewUrl;
      video && window.open(video);
    }
  };
  // 上传视频
  const handleUploadVideo = (d) => {
    if (d.file && d.file.status === "uploading") {
      loadingSet(true);
      // 抓取不到错误状态，上传错误的时候恢复状态
      setTimeout(() => {
        loadingSet(false);
      }, 5000);
    } else {
      loadingSet(false);
    }
    if (d.file && d.file.status === "removed") {
      onChange([]);
      return false;
    }
    if (d.file && d.file.status === "done" && d.file.response) {
      let data = d.file.response;
      onChange(d.fileList);
      if (!data.cover) {
        message.error("获取封面图失败");
        return;
      }
    }
  };
  return (
    <DJOssUpload
      onChange={handleUploadVideo}
      onPreview={handlePreview}
      fileList={fileList}
      {...restProps}
    >
      {fileList && fileList.length > 0 ? null : loading ? (
        <div>
          <Icon type="loading" />
          <div className="ant-upload-text">上传中...</div>
        </div>
      ) : (
        <div>
          <Icon type="plus" />
          <div className="ant-upload-text">请上传视频</div>
        </div>
      )}
    </DJOssUpload>
  );
};
